package com.lanyun.oss.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

public class AliyunOssStorageService implements StorageService {
    private final String endpoint;
    private final String accessKeyId;
    private final String accessKeySecret;
    private final String bucketName;

    public AliyunOssStorageService(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.bucketName = bucketName;
    }

    @Override
    public String uploadFile(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            String fileName = file.getOriginalFilename();
            ossClient.putObject(bucketName, fileName, file.getInputStream());
            return "https://" + bucketName + "." + endpoint + "/" + UUID.randomUUID() + "-" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("Failed to upload file to Aliyun OSS", e);
        } finally {
            ossClient.shutdown();
        }
    }

    @Override
    public String uploadFileByPId(MultipartFile file, String type, String productId) {
        return null;
    }
}